package intranet.controllers;
import org.springframework.web.servlet.ModelAndView;
import intranet.models.*;
import intranet.tools.*;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MyGroupController extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/* IsNumber Function */
	public static boolean IsNumber(String num) {
        try {
            Integer.parseInt(num);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
	@RequestMapping("/sharing_groups.html")
	public ModelAndView MyGroups(HttpServletRequest request, HttpServletResponse response,HttpSession session,String error_msg ) throws SQLException,ServletException, IOException{
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){
			MyGroups groupModel=new MyGroups();
			ResultSet rst=groupModel.SelectMyGroups(Integer.parseInt(session.getAttribute("user_id").toString()));
			ArrayList groupList=resultSetToArrayList(rst);
			mv.addObject("includethispage", "file_sharing/mygroups/my_groups.jsp");
			
			mv.addObject("curUser",session.getAttribute("user_name"));
			mv.addObject("grouplist",groupList);
			//IF Error Occurred, passing error message to page
			mv.addObject("error_msg",error_msg);
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	@RequestMapping("/delete_group.html")
	public ModelAndView DeleteGroup(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException,ServletException, IOException{
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){
			String id= request.getParameter("group_id");
			MyGroups groupModel=new MyGroups();
			id=(IsNumber(id)?id:"0");
			if(Integer.parseInt(id)==0){
				mv.addObject("includethispage", "not_accessible_page.jsp");
				return mv;
			}else{
				// Verify File Owner
				if(groupModel.isOwner(Integer.parseInt(session.getAttribute("user_id").toString()), Integer.parseInt(id))==false){
					mv.addObject("includethispage", "not_accessible_page.jsp");
					return mv;
				}
				groupModel.DeleteMyGroups(Integer.parseInt(id));
				response.sendRedirect("sharing_groups.html");
			}
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	@RequestMapping("/view_members.html")
	public ModelAndView ViewMember(HttpServletRequest request, HttpServletResponse response,String error_msg,String group_id,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){	
			String groupID=(group_id=="")?request.getParameter("group_id"):group_id;
			if(!IsNumber(groupID)){
				mv.addObject("includethispage", "not_accessible_page.jsp");
				return mv;
			}else{
				MyGroups myMod=new MyGroups();
				// Verify IF MEMBER OF THE GROUP
				/*if(myMod.isOwner(Integer.parseInt((String)session.getAttribute("user_id")), Integer.parseInt(groupID))==false){
					mv.addObject("includethispage", "not_accessible_page.jsp");
					return mv;
				}*/
				
				//Passing Page Included
				mv.addObject("includethispage", "file_sharing/mygroups/group_members.jsp");
				//Passing groupID
				mv.addObject("groupid",groupID);
				//Passing Members
				ResultSet rstuser=myMod.SelectMembers(Integer.parseInt(groupID));
				ArrayList arruser=this.resultSetToArrayList(rstuser);
				mv.addObject("users", arruser);
				
				//Get Group Owner ID and Pass to Page
				int ownerId=0;
				String groupName="";
				ResultSet groupRst=myMod.SelectGroupOwner(Integer.parseInt(groupID));
				while(groupRst.next()){
					ownerId=groupRst.getInt("GROUP_OWNER");
					groupName=groupRst.getString("GROUP_NAME");
				}
				mv.addObject("groupname", groupName);
				//Passing Owner ID and Current User ID
				mv.addObject("ownerid", ownerId);
				mv.addObject("curuserid", session.getAttribute("user_id"));
				
				//Passing String of User Names
				MyuploadModel myUpload=new MyuploadModel();
				String usernames=myUpload.SelectUsers();
				mv.addObject("usernames",usernames);
				
				//IF Error Occurred, passing error message to page
				mv.addObject("error_msg",error_msg);
				
			}
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	@RequestMapping(value="/add_member.html",method = RequestMethod.POST)
	public ModelAndView AddGroupMember(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView();
		if(session.getAttribute("user_id")!=null){	
			MyuploadModel myMod=new MyuploadModel();
			MyGroups groupModel=new MyGroups();
			String error_msg="";
			String user_name=request.getParameter("txtusername");
			String group_id="";
			int user_id=myMod.getUserIdByUserName(user_name);
			if(request.getParameter("btnmember")!=""){
				group_id=request.getParameter("txtgroupid");
				if(user_name.isEmpty()){
					error_msg="Please enter user name";
					mv=this.ViewMember(request, response, error_msg,group_id,session);
					return mv;
				}else if(user_id==0){
					error_msg="Incorrect user name, please try again";
					mv=this.ViewMember(request, response, error_msg,group_id,session);
					return mv;
				}else if(groupModel.isExistingMember(user_id,group_id)){
					error_msg="The user name '"+user_name+"' has been added already";
					mv=this.ViewMember(request, response, error_msg,group_id,session);
					return mv;
				}else{
					// Add Group Member
					groupModel.AddMember(Integer.parseInt(group_id),user_id);
					mv=this.ViewMember(request, response, error_msg,group_id,session);
				}
			}

		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	@RequestMapping("/delete_member.html")
	public ModelAndView DeleteMember(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){	
			String group_id= request.getParameter("group_id");
			String user_id= request.getParameter("user_id");
			MyGroups groupModel=new MyGroups();
			group_id=(IsNumber(group_id)?group_id:"0");
			user_id=(IsNumber(user_id)?user_id:"0");
			if(Integer.parseInt(group_id)==0 ||Integer.parseInt(user_id)==0 ){
				mv.addObject("includethispage", "not_accessible_page.jsp");
				return mv;
			}else{
				// Verify Group Owner
				if(groupModel.isOwner(Integer.parseInt(session.getAttribute("user_id").toString()), Integer.parseInt(group_id))==false){
					mv.addObject("includethispage", "not_accessible_page.jsp");
					return mv;
				}else if(Integer.parseInt(session.getAttribute("user_id").toString())==Integer.parseInt(user_id)){
					mv.addObject("includethispage", "not_accessible_page.jsp");
					return mv;
				}
				groupModel.DeleteMember(Integer.parseInt(group_id),Integer.parseInt(user_id));
				response.sendRedirect("view_members.html?group_id="+group_id);
			}
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	//Add New Groups
		@RequestMapping("/add_group.html")
		public ModelAndView NewGroup(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException,ServletException, IOException{
			ModelAndView mv=new ModelAndView();
			if(session.getAttribute("user_id")!=null){		
				String group_name= request.getParameter("txtgroup");
				MyGroups groupModel=new MyGroups();
				String error_msg="";
				if(group_name.isEmpty()){
					error_msg="Please enter group name";
					mv=this.MyGroups(request, response,session,error_msg);
					return mv;
				}else if(groupModel.isExistingGroupName(group_name)){
					error_msg="The group name '"+group_name+"' has been added already";
					mv=this.MyGroups(request, response,session,error_msg);
					return mv;
				}else{
					// Add Group
					groupModel.InsertGroup(group_name, Integer.parseInt(session.getAttribute("user_id").toString()));
					mv=this.MyGroups(request, response,session,error_msg);
				}
			}else{
				response.sendRedirect("login.html");
			}
			return mv;
		}
		//Save Groups
		@RequestMapping("/update_group.html")
		public void UpdateGroup(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException,ServletException, IOException{
			if(session.getAttribute("user_id")!=null){		
				String group_name= request.getParameter("group_name");
				String group_id= request.getParameter("group_id");
				MyGroups groupModel=new MyGroups();
				groupModel.UpdateGroup(Integer.parseInt(group_id), group_name);
				response.sendRedirect("sharing_groups.html");
			}else{
				response.sendRedirect("login.html");
			}
		}
		
	// RESULTSET TO ARRAYLIST
	   public ArrayList resultSetToArrayList(ResultSet rs) throws SQLException{
		    ResultSetMetaData md = rs.getMetaData();
		    int columns = md.getColumnCount();
		    ArrayList results = new ArrayList();
		    while (rs.next()){
		    HashMap row = new HashMap();
		    results.add(row);
			    for(int i=1; i<=columns; i++){
			    row.put(md.getColumnName(i),rs.getObject(i));
			    }
		    }
		    return results;
	    }
}